package com.cloud.neo4j.common.neo4j;

import com.cloud.neo4j.business.dto.result.ResultEntity;
import org.neo4j.driver.Record;
import org.neo4j.driver.types.Node;
import org.neo4j.driver.types.Relationship;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 处理neo4j返回的数据集合
 * @author 刘房
 */
public class Neo4jResponse {

    /**
     * 处理Neo4j返回的数据集合
     * @param list  Neo4j查询结果
     * @return  List<ResultEntity>
     */
    public static List<ResultEntity> getResultEntity(List<Record> list){
        List<ResultEntity> resultEntityList = new ArrayList<>();
        if(list.size() < 1) {
            return null;
        }
        /** 处理数据 */
        for (int i = 0; i < list.size(); i++) {
            Record record = list.get(i);
            ResultEntity resultEntity = new ResultEntity();
            resultEntity.setNodeOne(setNodeCov(record.get("n1").asNode()));
            resultEntity.setRelationship(setRelationshipCov(record.get("r").asRelationship()));
            resultEntity.setNodeTwo(setNodeCov(record.get("n2").asNode()));
            resultEntityList.add(resultEntity);
        }
        return resultEntityList;
    }

    /**
     * Node转换
     * @param node  节点结果转换
     * @return  map
     */
    public static Map<String,Object> setNodeCov(Node node){
        Map<String, Object> nodeOne = new HashMap<>();
        nodeOne.putAll(node.asMap());
        nodeOne.put("id",node.id());
        nodeOne.put("labels",node.labels());
        return nodeOne;
    }

    /**
     * Relationship结果转换
     * @param relationship  关系结果转换
     * @return  map
     */
    public static Map<String,Object> setRelationshipCov(Relationship relationship){
        Map<String, Object> relationshipMap = new HashMap<>();
        relationshipMap.putAll(relationship.asMap());
        relationshipMap.put("id",relationship.id());
        relationshipMap.put("endNodeId",relationship.endNodeId());
        relationshipMap.put("startNodeId",relationship.startNodeId());
        relationshipMap.put("type",relationship.type());
        return relationshipMap;
    }
}
